package com.openthinks.joyniproject.utils;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 基础工具类
 * @author Cloud
 *
 */
public class BaseUtil {

	private static Logger logger = Logger.getLogger(BaseUtil.class);
	
	/**
	 * 转换字符串为Long. data为null,""或非数字时返回null
	 * @param data
	 * @return
	 */
	public static Long parseLong(String data) {
		
		try {
			return StringUtils.isEmpty(data) ? null : Long.parseLong(data);
		} catch (Exception e) {
			logger.warn("转换数字时出错", e);
			return null;
		}
	}
	
	/**
	 * 转换字符串为Long. data为null,""或非数字时返回null
	 * @param data
	 * @return
	 */
	public static Integer parseInt(String data) {
		
		try {
			return StringUtils.isEmpty(data) ? null : Integer.parseInt(data);
		} catch (Exception e) {
			logger.warn("转换数字时出错", e);
			return null;
		}
	}
	
	/**
	 * 转换对象为String null => null, 其他 => data.toString()
	 * @param data
	 * @return
	 */
	public static String parseString(Object data) {
		
		return data == null ? null : data.toString();
	}
	
	/**
	 * 判断数组是否全不为空. String对比"", Map, Collect, Array对比length=0,其余对比null
	 * @param objs
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNotEmpty(Object... objs) {
		
		if (objs == null || objs.length == 0) {
			return false;
		}
		
		boolean ret = true;
		for (Object obj : objs) {
			if (obj == null) {
				ret = false;
			} else if (obj instanceof String) {
				String temp = (String)obj;
				if ("".equals(temp.trim())) {
					ret = false;
				}
			} else if (obj instanceof Collection) {
				Collection temp = (Collection)obj;
				if (temp.size() == 0) {
					ret = false;
				}
			} else if (obj instanceof Map) {
				Map temp = (Map)obj;
				if (temp.size() == 0) {
					ret = false;
				}
			} else if (isArray(obj)) {
				if (Array.getLength(obj) == 0) {
					ret = false;
				}
			}
			
			if (!ret) {
				break;
			}
		}
		
		return ret;
	}
	
	/**
	 * 判断对象是否是数组，支持基本类型数组
	 * @param obj
	 * @return
	 */
	private static boolean isArray(Object obj) {
		
		return obj.getClass().isArray();
	}
}
